#include "vcd-ping.h"

#include <gio/gio.h>

#ifdef __linux__
extern struct StVcdPingCtx g_vcd_ping_linux;
#endif

#ifdef __WIN32__
extern struct StVcdPingCtx g_vcd_ping_win32;
#endif

#ifdef __APPLE__

#endif


gboolean vcd_ping_start(VCD_PING_CALLBACK callback, gpointer priv){
#ifdef __linux__
    g_vcd_ping_linux.start(callback,priv);
#endif

#ifdef __WIN32__
    g_vcd_ping_win32.start(callback,priv);
#endif

#ifdef __APPLE__

#endif
    return TRUE;
}

void     vcd_ping_stop(){
#ifdef __linux__
    g_vcd_ping_linux.stop();
#endif

#ifdef __WIN32__
    g_vcd_ping_win32.stop();
#endif

#ifdef __APPLE__

#endif
}

gboolean vcd_ping_is_port_open(const char* host,guint port){

    if(!host) return FALSE;

	GError*  err = NULL;
	GSocket *socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,G_SOCKET_PROTOCOL_TCP,&err);
	GSocketAddress *addr = g_inet_socket_address_new_from_string(host,port);
	if(!addr)
		goto failed;

	err = NULL;
	g_socket_set_blocking(socket,0);
    g_socket_connect(socket,addr,NULL,&err);

    err = NULL;
    g_socket_condition_timed_wait(socket,G_IO_IN | G_IO_OUT | G_IO_NVAL | G_IO_ERR | G_IO_HUP, 1000*200,NULL,&err);
    if(err)
    	goto failed;

    err = NULL;
    g_socket_check_connect_result(socket,&err);
    if(err)
		goto failed;    	

    g_socket_close(socket,&err);

	return TRUE;
failed:
	if(socket){
		err = NULL;
		g_socket_close(socket,&err);
	}
	if(addr)
		g_object_unref(addr);

	return FALSE;
}
